package com.jinzhi.eventresource.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.eventresource.main.TemplateCertificateDO;
import com.jinzhi.eventresource.service.TemplateCertificateService;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/jzweb/eventResourceTemplateDetails")
public class TemplateDetailController extends BaseController {
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private TemplateCertificateService templateCertificateService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private ItemBankTkService itemBankTkService;

    /**
     * 获取所有知识点题型 题目数量和分值
     * 依据相同profiledId分组
     *
     * @param id    试卷模板id
     * @param model 所有知识点题型的数量和分数
     * @return
     */
    @GetMapping("/{id}")
//    @RequiresPermissions("jzweb:templateDetail:templateDetail")
    String TemplateDetails(@PathVariable("id") Long id, Model model) {
        // template id 试卷模板
        model.addAttribute("tptemplateId", id);
        TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.selectById(id);

        // 获取总分
        model.addAttribute("totalScore", testPaperTemplateDO.getTotalScore());

        // 关联表 试卷模板id 证书id
        List<TemplateCertificateDO> templateCertificateList = templateCertificateService
                .selectList(new EntityWrapper<TemplateCertificateDO>()
                        .eq("paper_template_id", id));

        if (Objects.isNull(templateCertificateList)) {
            model.addAttribute("type", "");
            model.addAttribute("titleNumber", "");
            model.addAttribute("score", "");
            return "jzweb/eventTemplateDetail/eventTemplateDetail";
        }

        // 根据证书id 获取profiledId和grade
        List<CertificateNewsDO> certificateNewsDOList = templateCertificateList.stream()
                .map(templateCertificateDO -> certificateNewsService.selectById(templateCertificateDO.getCertificateNewsId()))
                .collect(Collectors.toList());

        // 根据证书获取所有知识点
        List<KnowledgePointsDO> knowledgePointsDOList = new ArrayList<>();
        for (CertificateNewsDO certificateNewsDO : certificateNewsDOList) {
            Map map1 = new HashMap();
            map1.put("profileId", certificateNewsDO.getProfileId());
            if (certificateNewsDO.getGrade() == 0) {
                map1.put("grade", "高级");
            } else if (certificateNewsDO.getGrade() == 1) {
                map1.put("grade", "中级");
            } else if (certificateNewsDO.getGrade() == 2) {
                map1.put("grade", "初级");
            }
            knowledgePointsDOList.addAll(knowledgePointsService.selByProidGrade(map1));
        }

        //根据profileId分组
        Map<Long, List<KnowledgePointsDO>> profileMap
                = knowledgePointsDOList.stream().distinct().collect(Collectors.groupingBy(KnowledgePointsDO::getProfileId));
        HashMap<String, List<KnowledgePointsDO>> certificateNameMap = new HashMap<>();
        // 计算知识点题目数量
        for (Long profileId : profileMap.keySet()) {
            List<KnowledgePointsDO> knowledgePointsDOS = profileMap.get(profileId);
            knowledgeInfo(id, knowledgePointsDOS);
            String name = certificateProfileService.selectById(profileId).getName();
            // 证书名称map
            certificateNameMap.put(name, knowledgePointsDOS);
        }
        model.addAttribute("resultMap", certificateNameMap);

        return "jzweb/eventTemplateDetail/eventTemplateDetail";
    }

    private void knowledgeInfo(Long id, List<KnowledgePointsDO> knowledgePointsDOS) {
        // 遍历知识点获取给类型题目分数 数量
        for (KnowledgePointsDO knowledgePointsDO : knowledgePointsDOS) {
            String gradeName = knowledgePointsDO.getName() + " (" + knowledgePointsDO.getGrade() + ")";
            knowledgePointsDO.setName(gradeName);
            // 计算题目数量
            getEventKnowss(knowledgePointsDO);
            // 查询试卷详情
            TemplateDetailsDO templateDetailsDO = templateDetailsService.findOneByKv("tptemplate_id", id,
                    "kpoints_id", knowledgePointsDO.getId(), "type", 0);
            if (templateDetailsDO != null) {
                // 题目数量 分数
                knowledgePointsDO.setSingleNum0(templateDetailsDO.getTitleNumber());
                knowledgePointsDO.setSingleNum0Score(templateDetailsDO.getScore());
            } else {
                knowledgePointsDO.setSingleNum0(null);
                knowledgePointsDO.setSingleNum0Score(null);
            }

            TemplateDetailsDO templateDetailsDO1 = templateDetailsService.findOneByKv("tptemplate_id", id,
                    "kpoints_id", knowledgePointsDO.getId(), "type", 1);
            if (templateDetailsDO1 != null) {
                knowledgePointsDO.setMultipleNum0(templateDetailsDO1.getTitleNumber());
                knowledgePointsDO.setMultipleNum0Score(templateDetailsDO1.getScore());
            } else {
                knowledgePointsDO.setMultipleNum0(null);
                knowledgePointsDO.setMultipleNum0Score(null);
            }

            TemplateDetailsDO templateDetailsDO2 = templateDetailsService.findOneByKv("tptemplate_id", id,
                    "kpoints_id", knowledgePointsDO.getId(), "type", 2);
            if (templateDetailsDO2 != null) {
                knowledgePointsDO.setJudgeNum0(templateDetailsDO2.getTitleNumber());
                knowledgePointsDO.setJudgeNum0Score(templateDetailsDO2.getScore());
            } else {
                knowledgePointsDO.setJudgeNum0(null);
                knowledgePointsDO.setJudgeNum0Score(null);
            }

        }
    }

    /**
     * 自动新增试卷详情
     *
     * @param tptemplateId
     * @param kpointsId
     * @param type
     * @param titleNumber
     * @param score
     * @return
     */
    @Log("修改模板详情")
    @ResponseBody
    @RequestMapping("/update")
//    @RequiresPermissions("jzweb:templateDetail:edit")
    public Result<String> update(String tptemplateId, String[] kpointsId, String[] type, String[] titleNumber, String[] score) {
        if (StringUtils.isBlank(tptemplateId)) {
            return Result.fail("缺少参数试卷模板id");
        }

        if (kpointsId != null && kpointsId.length > 0) {
            int nn = 0;
            List<TemplateDetailsDO> templateDetailsDOS = new ArrayList<>();
            List<Long> temIds = new ArrayList<>();
            for (int i = 0; i < type.length; i++) {
                TemplateDetailsDO templateDetailsDO = templateDetailsService.findOneByKv("tptemplate_id", Long.parseLong(tptemplateId), "kpoints_id", kpointsId[nn], "type", type[i]);
                if (StringUtils.isNotBlank(titleNumber[i]) && StringUtils.isNotBlank(score[i])) {
                    if (templateDetailsDO != null) {
                        templateDetailsDO.setTitleNumber(Integer.parseInt(titleNumber[i]));//题目数量
                        templateDetailsDO.setScore(Integer.parseInt(score[i]));//题目分值
                        templateDetailsDOS.add(templateDetailsDO);
                    } else {
                        TemplateDetailsDO templateDetailsDO1 = new TemplateDetailsDO();
                        templateDetailsDO1.setTptemplateId(Long.parseLong(tptemplateId));//试卷模板id
                        templateDetailsDO1.setKpointsId(Long.parseLong(kpointsId[nn]));//知识点id
                        templateDetailsDO1.setType(Integer.parseInt(type[i]));//题目类型
                        templateDetailsDO1.setTitleNumber(Integer.parseInt(titleNumber[i]));//题目数量

                        templateDetailsDO1.setScore(Integer.parseInt(score[i]));//题目分值
                        templateDetailsDO1.setState(0);//默认正常
                        templateDetailsDO1.setCreaterId(this.getUserId());//创建人id
                        templateDetailsDO1.setCreaterDate(new Date());//创建时间
                        templateDetailsDOS.add(templateDetailsDO1);
                    }

                } else if (StringUtils.isBlank(titleNumber[i]) && StringUtils.isBlank(score[i])) {
                    if (templateDetailsDO != null) {
                        temIds.add(templateDetailsDO.getId());
                    }
                } else {
                    KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(kpointsId[nn]);
                    String typess;
                    if (type[i].equals("0")) {
                        typess = "单选";
                    } else if (type[i].equals("1")) {
                        typess = "多选";
                    } else {
                        typess = "判断";
                    }
                    return Result.fail("知识点(" + knowledgePointsDO.getName() + ")中题目类型(" + typess + ")的题目数量或分值为空，请确保某一题目类型中两个值都填或都不填！");
                }

                if ((i + 1) % 3 == 0) {
                    nn = nn + 1;
                }
            }


            if (templateDetailsDOS.size() > 0) {
                boolean cc = templateDetailsService.insertOrUpdateBatch(templateDetailsDOS, templateDetailsDOS.size());
                if (!cc) {
                    return Result.fail("添加模板失败");
                }
            }

            if (temIds.size() > 0) {
                boolean ee = templateDetailsService.deleteBatchIds(temIds);
                if (!ee) {
                    return Result.fail("删除模板失败");
                }
            }

            return Result.ok();


        } else {
            return Result.fail("暂无知识点");
        }

    }

    /**
     * 各类型题库数量
     *
     * @param tptemplateId
     * @return
     */
    @ResponseBody
    @RequestMapping("/knowss")
    public Result<?> knowss(String tptemplateId) {
        if (StringUtils.isBlank(tptemplateId)) {
            return Result.fail("缺少参数试卷模板id");
        }
        return Result.ok(knowledgePointsService.knowss(tptemplateId));

    }

    public void getEventKnowss(KnowledgePointsDO knowledgePointsDO) {
        List<String> gradeList = Arrays.asList(knowledgePointsDO.getGrade().split(","));

        for (String grade : gradeList) {
            Map selectItemMap = new HashMap();
            selectItemMap.put("kpoints_id", knowledgePointsDO.getId());
            selectItemMap.put("grade", grade);

            CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(knowledgePointsDO.getProfileId());
            List<Map<Object, Object>> itemNum = null;
            // 如果是泰康知识点库则搜索itemBankTkService
            if (certificateProfileDO.getName().contains("泰康")) {
                itemNum = itemBankTkService.selNumByKpoints(selectItemMap);
            }else {
                itemNum = itemBankService.selNumByKpoints(selectItemMap);
            }

            // TODO 选最大值
            for (Map map : itemNum) {
                if (map.get("itemBankType").equals(0)) {
                    int num = Integer.parseInt(map.get("num").toString());
                    if (map.get("topicTypes").equals(0)) {
                        if (ObjectUtil.isNotNull(knowledgePointsDO.getMultipleNum2())) {
                            knowledgePointsDO.setSingleNum2(Math.max(num, knowledgePointsDO.getSingleNum2()));
                        }
                        knowledgePointsDO.setSingleNum2(num);
                    } else if (map.get("topicTypes").equals(1)) {
                        if (ObjectUtil.isNotNull(knowledgePointsDO.getMultipleNum2())) {
                            knowledgePointsDO.setMultipleNum2(Math.max(num, knowledgePointsDO.getMultipleNum2()));
                        }
                        knowledgePointsDO.setMultipleNum2(num);
                    } else {
                        if (ObjectUtil.isNotNull(knowledgePointsDO.getJudgeNum2())) {
                            knowledgePointsDO.setJudgeNum2(Math.max(num, knowledgePointsDO.getJudgeNum2()));
                        }
                        knowledgePointsDO.setJudgeNum2(num);
                    }
                }
            }
        }


    }


}
